package com.toutou.base.bindhelper

import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapShader
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.graphics.Shader
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import com.bumptech.glide.load.resource.bitmap.TransformationUtils
import java.security.MessageDigest


class GlideRoundTransform(dp: Float) : BitmapTransformation() {
    private var radius = 0f

    init {
        radius = Resources.getSystem().displayMetrics.density * dp
    }

    override fun transform(
        pool: BitmapPool,
        toTransform: Bitmap,
        outWidth: Int,
        outHeight: Int
    ): Bitmap {
        if(radius == 0f) {
            return toTransform
        }
        val bitmap = TransformationUtils.roundedCorners(pool, toTransform, radius.toInt())
        return roundCrop(pool, bitmap)!!
    }

    private fun roundCrop(pool: BitmapPool, source: Bitmap?): Bitmap? {
        if (source == null) return null

        val result = pool[source.width, source.height, Bitmap.Config.ARGB_8888]

        val canvas = Canvas(result)
        val paint = Paint()
        paint.setShader(
            BitmapShader(
                source,
                Shader.TileMode.CLAMP,
                Shader.TileMode.CLAMP
            )
        )
        paint.isAntiAlias = true
        val rectF = RectF(0f, 0f, source.width.toFloat(), source.height.toFloat())
        canvas.drawRoundRect(rectF, radius, radius, paint)
        return result
    }

    override fun toString(): String {
        return "GlideRoundTransform(radius=$radius)"
    }

    override fun equals(other: Any?): Boolean {
        return other is GlideRoundTransform &&
                other.radius == radius
    }

    override fun hashCode(): Int {
        return (ID.hashCode() + radius * 1000).toInt()
    }

    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
        messageDigest.update((ID + radius).toByteArray(CHARSET))
    }

    companion object {
        private const val ID = "GlideRoundTransform." + 1.0
    }
}